﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using StuMana.Services;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

namespace StuMana.UI
{
    public partial class Log_bookstore :Office2007Form
    {
        public Log_bookstore()
        {
            InitializeComponent();
        }

        DataTable tabPDF = new DataTable();
        student stu = new student();
        string queryLog = "";

        bool co = false;

        private System.Drawing.Font fontForAll = null;
        private StyleManager managerStyle = new DevComponents.DotNetBar.StyleManager();

        public void ReadSetting()
        {
            XmlReader reader = XmlReader.Create("Settings.xml");
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element
                && reader.Name == "font")
                {
                    string name = reader.GetAttribute(0).ToString();
                    string style = reader.GetAttribute(1).ToString();
                    float size = float.Parse(reader.GetAttribute(2).ToString());
                    if (style == "Bold")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Italic")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Regular")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Strikeout")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Strikeout, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    if (style == "Underline")
                        fontForAll = new System.Drawing.Font(reader.GetAttribute(0).ToString(), size, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    while (reader.NodeType != XmlNodeType.EndElement)
                    {
                        reader.Read();
                        if (reader.Name == "managerstyle" && reader.NodeType == XmlNodeType.Element)
                        {
                            reader.Read();
                            string stylemana = reader.Value.ToString();

                            if (stylemana == "Office2007Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Blue;
                            if (stylemana == "Office2007Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Silver;
                            if (stylemana == "Office2007Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007Black;
                            if (stylemana == "Windows7Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Windows7Blue;
                            if (stylemana == "Office2007VistaGlass")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2007VistaGlass;
                            if (stylemana == "Office2010Silver")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Silver;
                            if (stylemana == "Office2010Blue")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Blue;
                            if (stylemana == "Office2010Black")
                                managerStyle.ManagerStyle = DevComponents.DotNetBar.eStyle.Office2010Black;
                        }
                    }
                }
            }
            reader.Close();
        }

        public void ConfigSetting()
        {
            ReadSetting();
            for (int i = 0; i < Controls[0].Controls[0].Controls.Count; i++)
            {
                if (Controls[0].Controls[0].Controls[i] is LabelX)
                {
                    Controls[0].Controls[0].Controls[i].Font = fontForAll;
                }
            }

            for (int i = 0; i < Controls[0].Controls[1].Controls.Count; i++)
            {
                if (Controls[0].Controls[1].Controls[i] is LabelX)
                {
                    Controls[0].Controls[1].Controls[i].Font = fontForAll;
                }
            }
            styleManager1 = managerStyle;
        }
      
        private void Log_bookstore_Load(object sender, EventArgs e)
        {
            cmbExClass.Items.Add("All Class");
            cmbExClass.Items.Add("10A1");
            cmbExClass.Items.Add("10A2");
            cmbExClass.Items.Add("10A3");
            cmbExClass.Items.Add("10A3");
            cmbExClass.Items.Add("10A4");
            cmbExClass.Items.Add("10A5");
            cmbExClass.Items.Add("10A6");
            cmbExClass.Items.Add("10A7");
            cmbExClass.Items.Add("10A8");
            cmbExClass.Items.Add("10A9");

            cmbExClass.Items.Add("11A1");
            cmbExClass.Items.Add("11A2");
            cmbExClass.Items.Add("11A3");
            cmbExClass.Items.Add("11A4");
            cmbExClass.Items.Add("11A5");
            cmbExClass.Items.Add("11A6");
            cmbExClass.Items.Add("11A7");
            cmbExClass.Items.Add("11A8");
            cmbExClass.Items.Add("11A9");
            
            cmbExClass.Items.Add("12A1");
            cmbExClass.Items.Add("12A2");
            cmbExClass.Items.Add("12A3");
            cmbExClass.Items.Add("12A4");
            cmbExClass.Items.Add("12A5");
            cmbExClass.Items.Add("12A6");
            cmbExClass.Items.Add("12A7");
            cmbExClass.Items.Add("12A8");
            cmbExClass.Items.Add("12A9");
            
            cmbExClass.SelectedIndex = 0;
            ConfigSetting();           
        }

        private void btnXXemLog_Click(object sender, EventArgs e)
        {
            if (dgvXDanhSachSinhVien.SelectedRows.Count < 1)
            {
                {
                    MessageBoxEx.Show("Not choose any student", "Warning!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            else
            {
                dgvXLogBookStore.Columns.Clear();
                int tagID = int.Parse(dgvXDanhSachSinhVien.SelectedRows[0].Cells[0].Value.ToString());
                ConnectionController control = new ConnectionController();
                control.connection.Open();
                try
                {
                    MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                    cmd.CommandText = "SELECT l.ID,s.Name as Student ,b.Name ,b.Price,l.Date  FROM log_bookstore l , bookstore b , studentinfo s WHERE  l.TagID =s.TagID and l.ID_BookStore= b.ID  and s.TagID = " + tagID.ToString();
                    MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adap.Fill(ds);
                    dgvXLogBookStore.DataSource = ds.Tables[0].DefaultView;
                    tabPDF = ds.Tables[0];
                    stu.getStdInfo(tagID.ToString());
                    queryLog = "SELECT b.Name ,b.Price,l.Date  FROM log_bookstore l , bookstore b , studentinfo s WHERE  l.TagID =s.TagID and l.ID_BookStore= b.ID  and s.TagID = " + tagID.ToString();
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    if (control.connection.State == ConnectionState.Open)
                        control.connection.Clone();
                }
                if (dgvXLogBookStore.Rows.Count < 1)
                {
                    MessageBoxEx.Show("No result in BookStore for this student", "Information!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                int w1 = dgvXLogBookStore.Size.Width;
                int widthC1 = ((int)w1 / dgvXLogBookStore.Columns.Count);

                for (int i = 0; i < dgvXLogBookStore.Columns.Count; i++)
                {
                    dgvXLogBookStore.Columns[i].Width = widthC1;
                }
            }       
        }

        private void btnSearchTagID_Click(object sender, EventArgs e)
        {
            // reset log bookstore
            for (int i = dgvXLogBookStore.Rows.Count - 1; i > -1; i--)
            {
                dgvXLogBookStore.Rows.RemoveAt(i);
            }
             
            // search theo tagid
            string tagID = txtTagID.Text;
            if (tagID == "")
            {
                MessageBoxEx.Show("TagID invalid", "Warning!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int numberTagID = 0;
            bool flag = int.TryParse(tagID, out numberTagID);
            if (flag == false)
            {
                {
                    MessageBoxEx.Show("TagID invalid - TagID must be a number", "Warning!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }

            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT TagID,Name,Class,Account  FROM studentinfo WHERE TagID = " + tagID.ToString();
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                dgvXDanhSachSinhVien.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }

            if (dgvXDanhSachSinhVien.Rows.Count < 1)
            {
                {
                    MessageBoxEx.Show("No result - List Student ", "Information!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (dgvXDanhSachSinhVien.Columns.Count > 0)
            {
                int w = dgvXDanhSachSinhVien.Size.Width;
                int widthC = ((int)w / dgvXDanhSachSinhVien.Columns.Count);

                for (int i = 0; i < dgvXDanhSachSinhVien.Columns.Count; i++)
                {
                    dgvXDanhSachSinhVien.Columns[i].Width = widthC;
                }
            }
            co = true;
        }

        private void btnSearchClass_Click(object sender, EventArgs e)
        {
            // reset cafeteria 
            for (int i = dgvXLogBookStore.Rows.Count - 1; i > -1; i--)
            {
                dgvXLogBookStore.Rows.RemoveAt(i);
            }

            // search theo class
            string strClass = cmbExClass.Text.ToString();

            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                if (strClass == "All Class")
                {
                    cmd.CommandText = "SELECT TagID,Name,Class,Account  FROM studentinfo ";
                }
                else
                {
                    cmd.CommandText = "SELECT TagID,Name,Class,Account  FROM studentinfo WHERE Class = '" + strClass.ToString() + "'";
                }
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                dgvXDanhSachSinhVien.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }

            if (dgvXDanhSachSinhVien.Rows.Count < 1)
            {
                {
                    MessageBoxEx.Show("No result - List Student ", "Information!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (dgvXDanhSachSinhVien.Columns.Count > 0)
            {
                int w = dgvXDanhSachSinhVien.Size.Width;
                int widthC = ((int)w / dgvXDanhSachSinhVien.Columns.Count);

                for (int i = 0; i < dgvXDanhSachSinhVien.Columns.Count; i++)
                {
                    dgvXDanhSachSinhVien.Columns[i].Width = widthC;
                }
            }
            co = true;        
        }

        private void Log_bookstore_Resize(object sender, EventArgs e)
        {
            if (dgvXDanhSachSinhVien.Columns.Count>0)//(co == true)
            {
                int w = dgvXDanhSachSinhVien.Size.Width;
                int widthC = ((int)w / dgvXDanhSachSinhVien.Columns.Count);

                for (int i = 0; i < dgvXDanhSachSinhVien.Columns.Count; i++)
                {
                    dgvXDanhSachSinhVien.Columns[i].Width = widthC;
                }
            }

            if(dgvXLogBookStore.Columns.Count>0)// (co == true)
            {
                int w1 = dgvXLogBookStore.Size.Width;
                int widthC1 = ((int)w1 / dgvXLogBookStore.Columns.Count);

                for (int i = 0; i < dgvXLogBookStore.Columns.Count; i++)
                {
                    dgvXLogBookStore.Columns[i].Width = widthC1;
                }
            }
        }

        private void btnXSearchName_Click(object sender, EventArgs e)
        {
            // reset cafeteria            
            for (int i = dgvXLogBookStore.Rows.Count - 1; i > -1; i--)
            {
                dgvXLogBookStore.Rows.RemoveAt(i);
            }

            // search theo Name
            string strName = txtName.Text.ToString();
            if (strName == "")
            {
                MessageBoxEx.Show("Name invalid", "Warning!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ConnectionController control = new ConnectionController();
            control.connection.Open();
            try
            {
                MySql.Data.MySqlClient.MySqlCommand cmd = control.connection.CreateCommand();
                cmd.CommandText = "SELECT TagID,Name,Class,Account  FROM studentinfo WHERE Name like N'%" + strName.ToString() + "%'";
                MySql.Data.MySqlClient.MySqlDataAdapter adap = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adap.Fill(ds);
                dgvXDanhSachSinhVien.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (control.connection.State == ConnectionState.Open)
                    control.connection.Clone();
            }

            if (dgvXDanhSachSinhVien.Rows.Count < 1)
            {
                {
                    MessageBoxEx.Show("No result - List Student ", "Information!!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            if (dgvXDanhSachSinhVien.Columns.Count > 0)
            {
                int w = dgvXDanhSachSinhVien.Size.Width;
                int widthC = ((int)w / dgvXDanhSachSinhVien.Columns.Count);

                for (int i = 0; i < dgvXDanhSachSinhVien.Columns.Count; i++)
                {
                    dgvXDanhSachSinhVien.Columns[i].Width = widthC;
                }
            }
            co = true;
        }

        private void Log_bookstore_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void Log_bookstore_FormClosing(object sender, FormClosingEventArgs e)
        {
            Environment.Exit(Environment.ExitCode);
            Application.ExitThread();
            Application.Exit();
        }

        private void btnExportPDF_Click(object sender, EventArgs e)
        {
            if (tabPDF.Rows.Count > 0)
            {
                SaveFileDialog sfdlog = new SaveFileDialog();
                sfdlog.Filter = "PDF files (*.pdf)|*.pdf|All file (*.*)|*.*";
                sfdlog.FilterIndex = 1;
                DialogResult dlog = sfdlog.ShowDialog();
                if (dlog == DialogResult.OK)
                {
                    string name = sfdlog.FileName.ToString();
                    ExportToPdf(tabPDF, name);
                }
            }
            else
            {
                MessageBoxEx.Show("Log is empty ", " Warning !!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
        }

        public void ExportToPdf(DataTable dt, string path)
        {
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
            document.Open();
            
            iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

            //Full path to the Unicode Arial file
            string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");

            //Create a base font object making sure to specify IDENTITY-H
            BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            //Create a specific font object
            iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL);

            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Application.StartupPath + "\\images\\logo.jpg");

            logo.ScaleToFit(200f, 80f);

            PdfPTable infoLogo = new PdfPTable(2);
            float[] widthinfoLogo = new float[2];
            widthinfoLogo[0] = 10f;
            widthinfoLogo[1] = 10f;
            infoLogo.SetWidths(widthinfoLogo);
            infoLogo.WidthPercentage = 100;

            PdfPCell cellLogo = new PdfPCell(logo);
            cellLogo.Border = PdfPCell.NO_BORDER;
            // cellLogo.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            infoLogo.AddCell(cellLogo);

            PdfPCell cellDate = new PdfPCell(new Phrase(" Ngày " + DateTime.Today.Day.ToString() + " Tháng " + DateTime.Today.Month.ToString() + " Năm " + DateTime.Today.Year.ToString(), f));
            cellDate.Border = PdfPCell.NO_BORDER;
            cellDate.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            cellDate.VerticalAlignment = PdfPCell.ALIGN_BOTTOM;
            infoLogo.AddCell(cellDate);

            document.Add(infoLogo);

            Paragraph para = new Paragraph(" LOG BOOKSTORE \n ");
            para.Alignment = 1;
            document.Add(para);

            PdfPTable infoStu = new PdfPTable(2);
            PdfPRow rowInfo = null;
            float[] widthColInfo = new float[2];
            widthColInfo[0] = 10f;
            widthColInfo[1] = 10f;
            infoStu.SetWidths(widthColInfo);
            infoStu.WidthPercentage = 100;
            PdfPCell cellName = new PdfPCell(new Phrase("Name : " + stu.Name.ToString(), f));
            cellName.Border = PdfPCell.NO_BORDER;
            cellName.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            infoStu.AddCell(cellName);

            PdfPCell cellTagID = new PdfPCell(new Phrase("TagID : " + stu.TagID.ToString(), f));
            cellTagID.Border = PdfPCell.NO_BORDER;
            cellTagID.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
            infoStu.AddCell(cellTagID);

            PdfPCell cellClass = new PdfPCell(new Phrase("Class : " + stu.Class.ToString(), f));
            cellClass.Border = PdfPCell.NO_BORDER;
            cellClass.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            infoStu.AddCell(cellClass);

            PdfPCell cellAccount = new PdfPCell(new Phrase("Account : " + stu.Account.ToString() + "\n", f));
            cellAccount.Border = PdfPCell.NO_BORDER;
            cellAccount.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
            infoStu.AddCell(cellAccount);
            document.Add(infoStu);

            // cach dong 
            Paragraph info = new Paragraph("\n");
            document.Add(info);

            PdfPTable table = new PdfPTable(dt.Columns.Count -2 );
            PdfPRow row = null;

            float[] widths = new float[dt.Columns.Count -2 ];
            for (int i = 0; i < dt.Columns.Count -2 ; i++)
            {
                widths[i] = 4f;
            }

            table.SetWidths(widths);

            table.WidthPercentage = 100;
            int iCol = 0;
            string colname = "";
            PdfPCell cell = new PdfPCell(new Phrase("Products"));

            cell.Colspan = dt.Columns.Count;

            int count = 1;
            foreach (DataColumn c in dt.Columns)
            {
                if (count > 2)
                {
                    table.AddCell(new Phrase(c.ColumnName, f));
                }
                count++;
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    for (int i = 2; i < dt.Columns.Count - 1; i++) // bo 2 cot dau tien 
                    {
                        table.AddCell(new Phrase(r[i].ToString(), f));

                    }
                    table.AddCell(new Phrase(((DateTime)r[dt.Columns.Count - 1]).ToString("yyyy-MM-dd"), f));
        
                }
            } 
            document.Add(table);
            document.Close();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (tabPDF.Rows.Count < 1)
            {
                MessageBoxEx.Show("Log is empty ", " Warning !!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                Preview pre = new Preview();
                pre.stu = stu;
                pre.query = queryLog;
                pre.previewName = "LOG BOOKSTORE";
                pre.Show();
            }
        }           
    }
}
